// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package file

import (
	"audio-server/internal/model"
	"context"
	"database/sql"
	"encoding/json"
	"time"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type FileAddDirLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFileAddDirLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileAddDirLogic {
	return &FileAddDirLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FileAddDirLogic) FileAddDir(req *types.FileDirReq) (resp bool, err error) {
	fileModel := model.NewSysFileModel(l.svcCtx.Conn)
	name := req.Name
	parentId := req.ParentId
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	file := model.SysFile{
		Name:       name,
		ParentId:   parentId,
		UpdateTime: time.Now(),
		IsDir:      sql.NullInt64{Int64: 1, Valid: true},
		Path:       "/" + name,
	}
	if parentId > 0 {
		parentFile, err := fileModel.FindOne(l.ctx, parentId)
		if err == nil {
			file.Path = parentFile.Path + "/" + name
		}
	}

	file.UserId = sql.NullInt64{Int64: userId, Valid: true}

	_, err = fileModel.Insert(l.ctx, &file)
	if err != nil {
		return false, err
	}
	return true, nil
}
